package com.alibobo.tech5.sixenine;

import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import com.alibobo.tech5.ganji.CalendarHelper;
import com.alibobo.tech5.ganji.GJR;
import com.alibobo.tech5.sixenine.internal.PanKey;
import com.alibobo.tech5.sixenine.pan69.Pan69;
import com.alibobo.tech5.sixenine.pan69.PanEntry;

public class SixNinePanCreator {
	GanJiResourceManager _gm = null;

	public void setResManager(GanJiResourceManager gm) {
		_gm = gm;
	}

	public Pan69 createFrom(Date date, String 時) {
		String 月將 = CalendarHelper.getMonGeneral(date);
		List<String> ganjis = CalendarHelper.getDayGanJi(date);

		String 日干支 = ganjis.get(2);
		String 月干支 = ganjis.get(1);
		String 年干支 = ganjis.get(0);

		Pan69 pan = createFrom(日干支, 時, 月將);
		pan.set年干支(年干支);
		pan.set月干支(月干支);
		return pan;
	}

	public Pan69 createFrom(String 日干支, String 時, String 月將) {
		int mid = GJR.jiId(月將);
		int hid = GJR.jiId(時);
		int off = (mid - hid + 12) % 12;
		Pan69 bp = createFrom(日干支, off);
		update天將(bp, 時);
		bp.set月將(月將);
		bp.prepareStep2();
		return bp;
	}

	public Pan69 createFrom(String 日干支, int offset) {

		Hashtable<String, Object> shortPan = _gm.getPanBy(日干支, offset);
		Pan69 pan = new Pan69();

		pan.set日干支((String) shortPan.get(PanKey.日干支));
		Integer panOffset = (Integer) shortPan.get(PanKey.panOffset);
		pan.setPanOffset(panOffset);
		Integer 發用課 = (Integer) shortPan.get(PanKey.發用課);
		pan.set發用課(發用課);
		String 三傳 = (String) shortPan.get(PanKey.三傳);
		pan.set三傳(三傳);
		pan.set日貴((List<String>) shortPan.get(PanKey.日貴));
		pan.set夜貴((List<String>) shortPan.get(PanKey.夜貴));
		pan.setNotes((String) shortPan.get(PanKey.notes));
		pan.prepareStep1();
		return pan;
	}

	/*********************************************************
	 * 
	 * @param p
	 * @param 時
	 *********************************************************/
	protected void update天將(Pan69 p, String 時) {

		String 時干支 = GJR.五鼠遁(p.get日干(), 時);
		p.set時干支(時干支);

		Boolean isDay = GJR.isDay(時);

		List<String> conf = null;
		if (isDay) {
			conf = p.get日貴();
		} else {
			conf = p.get夜貴();
		}

		String 起位 = conf.get(0);
		String 順逆 = conf.get(1);
		List<String> 天將seq;
		if ("順".equals(順逆)) {
			天將seq = GJR.天將();
		} else {
			天將seq = GJR.天將逆行();
		}

		int id = GJR.jiId(起位);
		for (int i = 0; i < 12; i++) {
			PanEntry pe = p.get盤位(i);
			pe.set天將(天將seq.get(i));
		}
	}

}
